package sword_offer;

public class _05ReplaceSpace {

    public static void main(String[] args) {
        String str = "We are happy.";
        String replaceSpace = new _05ReplaceSpace().replaceSpace(str);
        System.out.println(replaceSpace);
    }

    public String replaceSpace(String s) {
        int targetLength = s.length();
        // 统计一遍共有多少个空格，得出目标长度
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ')
                targetLength += 2;
        }

        // 倒序填充
        char[] chars = new char[targetLength];
        int size = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' '){
                chars[size++] = '%';
                chars[size++] = '2';
                chars[size++] = '0';
            }else {
                chars[size++] = s.charAt(i);
            }
        }
        // chars转string
        return new String(chars);
    }

}
